package com.gtl.meishi.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.gtl.meishi.R;
import com.gtl.meishi.adapter.GridViewAdapter;
import com.gtl.meishi.bean.CotegroyEntity;
import com.gtl.meishi.bean.MediaEntity;
import com.gtl.meishi.model.MediaModel;
import com.gtl.meishi.ui.DetailActivity;
import com.gtl.meishi.util.HttpURLUtil;

import java.util.ArrayList;
import java.util.List;

public class HotFragment1 extends Fragment {

    private CotegroyEntity cotegroyEntity;

    public CotegroyEntity getCotegroyEntity() {
        return cotegroyEntity;
    }

    public HotFragment1 setCotegroyEntity(CotegroyEntity cotegroyEntity) {
        this.cotegroyEntity = cotegroyEntity;
        return this;
    }

    private GridView mGridView;
    private GridViewAdapter adapter;
    private List<MediaEntity> entityList = new ArrayList<>();
    private PullToRefreshGridView mPullToRefreshGridView;
    private boolean isBottom=false;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    List<MediaEntity> list = (List<MediaEntity>) msg.obj;
                    entityList.addAll(list);
                    if (page == 1) {
                        adapter = new GridViewAdapter(entityList, getActivity());
                        mGridView.setAdapter(adapter);
                    } else {
                        entityList.addAll(list);
                       mGridView.setSelection(entityList.size()-1);
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case 1:
                    list = (List<MediaEntity>) msg.obj;
                    entityList.add(0,list.get(0));
                    adapter.notifyDataSetChanged();
                    break;
            }
            mPullToRefreshGridView.onRefreshComplete();
        }
    };

    private int page = 1;
    String URL=null;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.activity_hot_fragment1, container, false);
        mPullToRefreshGridView = (PullToRefreshGridView) v.findViewById(R.id.pull_to_refresh_gridview);
        mPullToRefreshGridView.setMode(PullToRefreshBase.Mode.BOTH);
        mGridView = mPullToRefreshGridView.getRefreshableView();
        mGridView.setNumColumns(2);
        mGridView.setHorizontalSpacing(5);
        mGridView.setVerticalSpacing(5);
        URL = getURL(getCotegroyEntity());
        MediaModel.getList(handler, URL, getContext(), page, getCotegroyEntity());
        setListen();
        return v;
    }

    public String getURL(CotegroyEntity cotegroyEntity) {
        String url = HttpURLUtil.BASE_URL;
        switch (cotegroyEntity.getType()) {

            case 1:
                url += HttpURLUtil.HOT_VIDEO_LIST_URL;
                break;
            default:
                url += HttpURLUtil.VIDEO_LIST + "";
                break;

        }

        return url;


    }


    public void setListen() {
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), DetailActivity.class);
                MediaEntity mediaEntity = (MediaEntity) mGridView.getItemAtPosition(i);
                MediaEntity.MediaBean media = mediaEntity.getMedia();
                if (media != null) {
                    intent.putExtra("video", media.getVideo());
                    intent.putExtra("likes_count", media.getLikes_count());
                    intent.putExtra("caption", media.getCaption());
                    startActivity(intent);

                } else {
                    Toast.makeText(getActivity(), "非视频资源", Toast.LENGTH_SHORT).show();
                }
            }
        });
        refreshListen();
    }

    /**
     * 刷新监听的方式
     */
    private void refreshListen() {

        mPullToRefreshGridView.setOnPullEventListener(new PullToRefreshBase.OnPullEventListener<GridView>() {
            @Override
            public void onPullEvent(PullToRefreshBase<GridView> refreshView, PullToRefreshBase.State state, PullToRefreshBase.Mode direction) {

                //描述的过程从下拉到松手这样过程
                if (state.equals(PullToRefreshBase.State.PULL_TO_REFRESH)) {
                    //刚拉下拉标签名
                    refreshView.getLoadingLayoutProxy().setPullLabel("pull");
                    //下拉到一定程度
                    refreshView.getLoadingLayoutProxy().setReleaseLabel("release");
                    //松手加载
                    refreshView.getLoadingLayoutProxy().setRefreshingLabel("loding");
                    //时间
                    String time = DateUtils.formatDateTime(getContext(),
                            System.currentTimeMillis(),
                            DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                    refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(time);
                }
            }
        });

        /**
         * 下拉刷新
         */
        mPullToRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {

                    int pa= (int) Math.floor(Math.random()*(500+1));
                MediaModel.getListOne(handler, URL, getContext(), pa, getCotegroyEntity());
                Log.i("TAG","onPullDownToRefreshxial下拉刷新");
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {

                MediaModel.getList(handler, URL, getContext(), ++page, getCotegroyEntity());
                Log.i("TAG","onPullUpToRefresh上拉刷新");
            }
        });

        /**
         * 当gridview 上滑加载
         */
//        mPullToRefreshGridView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
//            @Override
//            public void onLastItemVisible() {
//                page=page++;
//                Log.i("TAG","setOnLastItemVisibleListener"+page);
//              //  MediaModel.getHot(handler, URL, getContext(), page, getCotegroyEntity());
//            }
//        });

//        mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(AbsListView absListView, int i) {
//
//            }
//
//            @Override
//            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
//                    if(i+i1==i2&&entityList.size()>0){
//                       isBottom=true;
//                    }
//            }
//        });

    }


}
